package com.songcha.library_webview.ui.fragment

import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.PopupWindow
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import com.songcha.library_base.base.BaseActivity
import com.songcha.library_base.base.BaseFragment
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.view.HeaderBarView
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_webview.R
import me.jessyan.autosize.AutoSize
import me.jessyan.autosize.AutoSizeCompat
import java.net.URL

open class WebViewFragment():BaseFragment(),HeaderBarView.IOnHeaderBarGoBackListener{
    private lateinit var mFlWebViewParent:FrameLayout
    protected lateinit var mHbvTitle:HeaderBarView
    private var mAgentWeb: AgentWeb?=null
    private var mTitle = ""
    protected var mWebView:WebView? = null

    override fun getLayoutId(): Int {
        return R.layout.webview_frag_webview
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        mFlWebViewParent = mRootView!!.findViewById(R.id.webview_fl_wv)
        mHbvTitle = mRootView!!.findViewById(R.id.webview_hbv_title)
        mHbvTitle.setOnGoBackListener(this)

        arguments.let {
            if(it == null) return@let
            val url=it.getString("url")?:return
            if(url.isBlank()) return@let
            mTitle = it.getString("title")?:""
            if(mTitle.isNotBlank())
                mHbvTitle.setTitle(mTitle)
            val titleColor=it.getInt("title_color",Color.BLACK)
            mHbvTitle.setTitleColor(titleColor)

            initWebView(url)

            AutoSize.autoConvertDensityOfGlobal(requireActivity())
        }

    }

    override fun onResume() {
        super.onResume()
        //webview will modify density,so need restore
        AutoSize.autoConvertDensityOfGlobal(requireActivity())
    }

    /* override fun isNeedShowLoadingDialog(): Boolean {
         return true
     }*/


    private fun initWebView(url:String){
        if(url.isBlank() || (!url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("file://"))){
            ToastUtil.show("无效的url地址")
            return
        }
        try{
            mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mFlWebViewParent, LinearLayout.LayoutParams(-1, -1))
                .closeIndicator()
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .createAgentWeb()
                .ready()
                .go(url)
            mWebView = mAgentWeb!!.webCreator.webView
            mWebView!!.settings.apply {
                javaScriptEnabled = true
                javaScriptCanOpenWindowsAutomatically = true
                //useWideViewPort = true
                loadWithOverviewMode = true
                mWebView!!.settings.cacheMode = WebSettings.LOAD_NO_CACHE
            }

        }catch (e:Exception) {
            e.printStackTrace()
        }

    }

    private val mWebViewClient: WebViewClient = object : WebViewClient() {
        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            //showLoadingDialog()
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            //hideLoadingDialog()
            if(view==null) return
            if(view==null) return
            if(mTitle.isBlank() && !url.isNullOrBlank()){
                mHbvTitle.setTitle(view!!.title?:"")
            }
        }

        override fun shouldInterceptRequest(
            view: WebView?,
            request: WebResourceRequest?
        ): WebResourceResponse? {
            if(request!=null){

            }
            return super.shouldInterceptRequest(view, request)
        }

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }


    }

    private val mWebChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {

        }

    }

    private fun loadUrl(url:String){
        if(url.isBlank() || (!url.startsWith("http://") && !url.startsWith("https://"))){
            return
        }
        mAgentWeb?.webCreator?.webView?.loadUrl(url)
    }

    /*private fun loadData(data:String){
        if(data.isBlank()){
            return
        }
        mAgentWeb?.webCreator?.webView?.loadData(data,"text/html","utf-8")
    }*/

    override fun onDestroy() {
        super.onDestroy()
        AutoSize.autoConvertDensityOfGlobal(requireActivity())
    }

    override fun onGoBack() {
        if(mAgentWeb==null){
            //finish()
        }else{
            if(mWebView!!.canGoBack()){
                mWebView!!.goBack()
            }else{
                //finish()
            }
        }
    }


}